#include "../include/GrassCluster.h"
#include <time.h>
#include <cstdlib>
#include <iostream>

GrassCluster::GrassCluster(GLfloat x, GLfloat y, GLfloat z, GLuint radius, GLuint density, Grass *grass) {
    this->x = x;
    this->y = y;
    this->z = z;
    this->radius = radius;
    this->density = density;
    this->grass = grass;

    vec3 *eye = new vec3();
    eye->x = 0.0; eye->y = 0.0; eye->z = 0.0;

    srand(time(NULL));
    for(int i =0; i < density ; i++){
        positions[i].x = x + ((float)(rand()%50)/50)*radius;
        positions[i].y = y;
        positions[i].z = z + ((float)(rand()%50)/50)*radius;
    }
/*
    int count = 0;
    int sampleCount = 0;
    int s = 0;
    int t = 0;
    sf::Vector2u v = splatMap.getSize();
    GLint width = v.x;
    emptyCluster = true;
    while(count < density){

        if(sampleCount < (radius*radius)){

            emptyCluster = false;
            s = x + ((float)(rand()%50)/50)*radius;
            t = z + ((float)(rand()%50)/50)*radius;

            GLfloat red = splatMap.getPixel(s,t).r;
            GLfloat green = splatMap.getPixel(s,t).g;
            GLfloat blue = splatMap.getPixel(s,t).b;

            //add a grass if not sand
            if(red == 0){

                positions[count].x = s;
                positions[count].z = t;
                positions[count].y = verts [(int)(s) + (int)(t)*(int)(width)].position[1];
            }
            count++;
            sampleCount++;
        }else{
            break;
        }
    }*/
}

void GrassCluster::render(vec3 camPos) {
    eyePos = camPos;
    vec3 pos;
    pos.x = x;
    pos.y = y;
    pos.z = z;
   // std::cout << "Drawing grass cluster at: " << x << " " << y << " " << z << std::endl;

    if(CG::euclidDistance(camPos, pos) >= (75+radius)) {
        return;
    }
    sortByDistance();
    for(int i = 0; i < density; i++) {
        glPushMatrix();
        glTranslatef(positions[i].x, positions[i].y, positions[i].z);
        grass->render(camPos, positions[i]);
        glPopMatrix();
    }
}
bool GrassCluster::comparePositions(vec3 p1, vec3 p2){
    return CG::euclidDistance(eyePos, p1) < CG::euclidDistance(eyePos, p2) ? true : false;
}
/*Make sure to set camPos in render so that it doesnt compare with (0,0,0)*/
void GrassCluster::sortByDistance(){

    //needs to be changed for a faster sort
   for(int i =0; i < density; i++){
         int max = i;
        for(int j=i+1; j < density; j++){
            bool dist = comparePositions(positions[max], positions[j]);
            if(dist){
           // std::cout << "got here" << std::endl;
            max = j;
            }
        }
        if(max != i){
        vec3 temp = positions[max];
        positions[max] = positions[i];
        positions[i] = temp;
        }
    }

    //std::sort(positions,positions+(sizeof(Position)*density));
}


